package com.hy.fangZhou.websocket;//package com.hy.websocket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
//访问服务端的url地址
@ServerEndpoint(value = "/websocket/{id}")
public class MyWebSocket {

    private static ConcurrentHashMap<String, MyWebSocket> webSocketSet = new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private static Logger log = LogManager.getLogger(MyWebSocket.class);
    private static String id = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id, Session session) {
        this.session = session;
        MyWebSocket.id = id;//接收到发送消息的人员编号
        //验证token 
        webSocketSet.put(id, this);     //加入set中
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO Error");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this.getId());  //从set中删除

    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.getMessage());
        error.printStackTrace();
    }

    private void sendMessage(String message) throws IOException {
        if (this.session.isOpen()) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 发送信息给指定ID用户，如果用户不在线则返回不在线信息给自己
     *
     * @param message
     * @param sendUserId
     * @throws IOException
     */
    public synchronized void sendtoUser(String message, String sendUserId) {

        try {
            if (webSocketSet.get(sendUserId) != null) {
                webSocketSet.get(sendUserId).sendMessage(message);
            } else {
                //如果用户不在线则返回不在线信息给自己
                sendtoUser("当前用户不在线", id);
            }
        } catch (IOException e) {
            log.info(message);
        }
    }

    /**
     * 发送信息给所有人
     *
     * @param message
     * @throws IOException
     */
    public void sendtoAll(String message) throws IOException {
        for (String key : webSocketSet.keySet()) {
            try {
                webSocketSet.get(key).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getId() {
        return id;
    }

    public static ConcurrentHashMap<String, MyWebSocket> getWebSocketSet() {
        return webSocketSet;
    }
}
